package algorithm.leetcode.simple;

/*
 使用栈实现队列
 */

import java.util.Stack;

/**
 * @author jack.wu
 * @version 1.0
 * @date 2020/10/21
 */
public class Question232 {

    public static void main(String[] args) {

    }

    class MyQueue {

        Stack<Integer> pushStack;
        Stack<Integer> popStack;

        /**
         * Initialize your data structure here.
         */
        public MyQueue() {
            pushStack = new Stack<>();
            popStack = new Stack<>();
        }

        /**
         * Push element x to the back of queue.
         */
        public void push(int x) {
           pushStack.push(x);
        }

        /**
         * Removes the element from in front of queue and returns that element.
         */
        public int pop() {
            shift();
            if (!popStack.isEmpty()) {
                return popStack.pop();
            }
            throw new RuntimeException("队列没有元素");
        }

        private void shift() {
            if (popStack.isEmpty()) {
                while (!pushStack.isEmpty()) {
                    popStack.push(pushStack.pop());
                }
            }
        }

        /**
         * Get the front element.
         */
        public int peek() {
           shift();
           if (!popStack.isEmpty()) {
               return popStack.peek();
           }
           throw new RuntimeException("队列没有元素");
        }

        /**
         * Returns whether the queue is empty.
         */
        public boolean empty() {
           return pushStack.isEmpty() && popStack.isEmpty();
        }
    }
}
